package Prism.core;

import java.util.*;

/**
* A simple FIFO based message store which allows a dynamic set of queue to be handled in the architecture. 
* Messages are always added to the end of the queue whereas they are removed at the head of the queue. 
* There is no knowledge of priorities.
*
*@version 2.0
*@author USC Soft. Arch. Group. Contact: Sam Malek <A HREF="mailto:malek@usc.edu"> malek@usc.edu </A>
*/
public class FIFOScheduler implements AbstractScheduler {
   
	/**
    * Store for the queue in the FIFO organized as a list (yb)
    */
//   Object queue[];
	Queue<Event> queue;
//   final static int DEFAULT_SIZE = 250;

	/**
    * Create the event store 
    */
   public FIFOScheduler()
   {
      queue = new LinkedList<Event>();
   }

   /**
    * Add an event to the beginning of the queue. The method is synchronized so that simultaneous
    * additions and removals are not possible. This is a potential major bottleneck.
    * @param m		Event to be added
    */

   public synchronized void add(Event evt)
   {
	  queue.add(evt);
      notifyAll();
   }

   /**
    * Get a message from the head of the queue and remove it from the message store, although the
    * message object itself is not deleted.
    * @return Message		The message object at the head of the FIFO
    */
   public synchronized Event getEvent()
   {
	   try {
		   while (isQueueEmpty())
			   wait();
	   }
	   catch (InterruptedException e) {
		   throw new RuntimeException(e);
	   }
	   
	   Event m = queue.remove();
	   notifyAll();
	   return m;
   }

   /**
    * Get the number of queued events waiting to be dispatched
    * @return int		Number of queue remaining
    */
   public synchronized int getWaitingLength()
   {
      return queue.size();
   }
   
   /**
    * Get a string representation of the message queue. This is used primarily for debugging
    * @return String 	The stringified representation of the queue.
    */
   public String toString()
   {
	   return "Fifo Scheduler Queue: " + queue.toString();
   }
 
   /**
    * Set the capacity of messages that can be stored before being dispatched
    * @param n		int the required capacity of the message store
    */

   public void setEventCapacity(int n)
   {
      // do not do anything since the capacity is dynamic
   }

   private boolean isQueueEmpty()
   {
      return queue.isEmpty();
   }
}



